﻿using DevExpress.ExpressApp.DC;
using EasyXaf.LowCode.WorkflowEditors.Models.Activities;
using System.ComponentModel;
using System.Xml.Linq;

namespace EasyXaf.LowCode.WorkflowEditors.Models;

[DomainComponent]
public abstract class Sequence : FlowObject, ISequence
{
    [Browsable(false)]
    public abstract IContainer Container { get; }

    [Browsable(false)]
    public IWorkflow Workflow { get; }

    [Browsable(false)]
    public ObjectCollection<IActivity> Activities { get; }

    ObjectCollection<IActivity> ISequence.Activities => Activities;

    public Sequence(IWorkflow workflow)
    {
        Workflow = workflow;
        Activities = new ObjectCollection<IActivity>(this);
    }

    public ISequence FindSequence(string sequenceId)
    {
        return Workflow.FindSequence(sequenceId, this);
    }

    public IActivity FindActivity(string activityId)
    {
        return Workflow.FindActivity(activityId, this);
    }

    public INode FindNode(string nodeId)
    {
        return Workflow.FindNode(nodeId, this);
    }

    public override void OnCreated()
    {
        base.OnCreated();

        Activities.Add(new StartActivity(Workflow, this).Created());
        Activities.Add(new EndActivity(Workflow, this).Created());
    }

    public override void OnCloned()
    {
        base.OnCloned();

        foreach (var activity in Activities)
        {
            activity.OnCloned();
        }
    }

    public override void WriteToXml(XElement element)
    {
        base.WriteToXml(element);

        if (Activities.Any())
        {
            var activitiesElement = new XElement("Activities");
            element.Add(activitiesElement);
            foreach (var activity in Activities)
            {
                var activityElement = new XElement(activity.GetType().Name);
                activity.WriteToXml(activityElement);
                activitiesElement.Add(activityElement);
            }
        }
    }

    public override void ReadFromXml(XElement element)
    {
        base.ReadFromXml(element);

        if (element.Element("Activities") is XElement activitiesElement)
        {
            foreach (var activityElement in activitiesElement.Elements())
            {
                Activities.Add(Workflow.CreateActivityFromXml(activityElement, this));
            }
        }
    }
}
